package com.volunteer.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.volunteer.entity.DemandApplication;
import com.volunteer.entity.PointRecord;
import com.volunteer.entity.ServiceDemand;
import com.volunteer.entity.VolunteerProfile;
import com.volunteer.mapper.DemandApplicationMapper;
import com.volunteer.mapper.PointRecordMapper;
import com.volunteer.mapper.ServiceDemandMapper;
import com.volunteer.mapper.VolunteerProfileMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 服务需求服务
 */
@Service
@RequiredArgsConstructor
public class DemandService {

    private final ServiceDemandMapper demandMapper;
    private final DemandApplicationMapper applicationMapper;
    private final PointRecordMapper pointRecordMapper;
    private final VolunteerProfileMapper volunteerProfileMapper;

    /**
     * 分页查询需求列表
     */
    public IPage<ServiceDemand> getDemandList(int page, int size, String status) {
        Page<ServiceDemand> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<ServiceDemand> queryWrapper = new LambdaQueryWrapper<>();
        
        if (status != null && !status.isEmpty()) {
            queryWrapper.eq(ServiceDemand::getStatus, status);
        }
        
        queryWrapper.orderByDesc(ServiceDemand::getCreateTime);
        return demandMapper.selectPage(pageParam, queryWrapper);
    }

    /**
     * 获取需求详情
     */
    public ServiceDemand getDemandById(Long id) {
        return demandMapper.selectById(id);
    }

    /**
     * 创建需求
     */
    public ServiceDemand createDemand(ServiceDemand demand) {
        if (demand.getStatus() == null) {
            demand.setStatus("PENDING");
        }
        demandMapper.insert(demand);
        return demand;
    }

    /**
     * 更新需求
     */
    public void updateDemand(ServiceDemand demand) {
        demandMapper.updateById(demand);
    }

    /**
     * 删除需求
     */
    public void deleteDemand(Long id) {
        demandMapper.deleteById(id);
    }

    /**
     * 申请需求
     */
    @Transactional
    public void applyDemand(Long demandId, Long userId, String reason) {
        // 检查是否已申请
        LambdaQueryWrapper<DemandApplication> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DemandApplication::getDemandId, demandId)
                .eq(DemandApplication::getUserId, userId);
        if (applicationMapper.selectCount(queryWrapper) > 0) {
            throw new RuntimeException("您已申请该需求");
        }

        // 创建申请记录
        DemandApplication application = new DemandApplication();
        application.setDemandId(demandId);
        application.setUserId(userId);
        application.setStatus("APPLIED");
        application.setReason(reason);
        applicationMapper.insert(application);
    }

    /**
     * 分配需求
     */
    @Transactional
    public void assignDemand(Long demandId, Long userId) {
        ServiceDemand demand = demandMapper.selectById(demandId);
        demand.setAssigneeId(userId);
        demand.setStatus("ASSIGNED");
        demandMapper.updateById(demand);

        // 更新申请状态
        LambdaQueryWrapper<DemandApplication> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DemandApplication::getDemandId, demandId)
                .eq(DemandApplication::getUserId, userId);
        DemandApplication application = applicationMapper.selectOne(queryWrapper);
        if (application != null) {
            application.setStatus("APPROVED");
            applicationMapper.updateById(application);
        }
    }

    /**
     * 完成需求并结算积分
     */
    @Transactional
    public void completeDemand(Long demandId) {
        ServiceDemand demand = demandMapper.selectById(demandId);
        demand.setStatus("COMPLETED");
        demandMapper.updateById(demand);

        // 发放积分
        if (demand.getAssigneeId() != null) {
            PointRecord pointRecord = new PointRecord();
            pointRecord.setUserId(demand.getAssigneeId());
            pointRecord.setPoints(demand.getPointsReward());
            pointRecord.setType("DEMAND");
            pointRecord.setSourceId(demandId);
            pointRecord.setDescription("完成需求：" + demand.getTitle());
            pointRecordMapper.insert(pointRecord);

            // 更新志愿者总积分
            LambdaQueryWrapper<VolunteerProfile> profileQuery = new LambdaQueryWrapper<>();
            profileQuery.eq(VolunteerProfile::getUserId, demand.getAssigneeId());
            VolunteerProfile profile = volunteerProfileMapper.selectOne(profileQuery);
            if (profile != null) {
                profile.setTotalPoints(profile.getTotalPoints() + demand.getPointsReward());
                volunteerProfileMapper.updateById(profile);
            }
        }
    }

    /**
     * 获取需求的申请列表
     */
    public List<DemandApplication> getDemandApplications(Long demandId) {
        LambdaQueryWrapper<DemandApplication> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DemandApplication::getDemandId, demandId)
                .orderByDesc(DemandApplication::getCreateTime);
        return applicationMapper.selectList(queryWrapper);
    }

    /**
     * 获取用户的申请记录
     */
    public List<DemandApplication> getUserApplications(Long userId) {
        LambdaQueryWrapper<DemandApplication> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DemandApplication::getUserId, userId)
                .orderByDesc(DemandApplication::getCreateTime);
        return applicationMapper.selectList(queryWrapper);
    }
}

